package com.jx.driving.protocol.terminal.codec;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 把流数据全部读取为字节数组
 * 
 * @author shenliuyang
 *
 *         2016年7月29日下午6:45:17
 */
public class TailByteArrayFieldReaderWriter extends FieldReaderWriter {

    private static final Logger logger = LoggerFactory.getLogger(TailByteArrayFieldReaderWriter.class);

    public TailByteArrayFieldReaderWriter(Field field, int size, int order) {
	super(field, size, order);
    }

    @Override
    public void read(InputStream in, Object to) throws IOException {
	byte[] buff = new byte[1024];
	int len;
	ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
	while ((len = in.read(buff)) != -1) {
	    out.write(buff, 0, len);
	}
	wrtietoField(to, out.toByteArray());
    }

    @Override
    public void write(OutputStream out, Object from) throws IOException {
	byte[] data = (byte[]) readFromField(from);
	if (data == null) {
	    return;
	}
	if (data.length > size) {
	    logger.warn("数据长度超过限制 {}  max {} 数据将会被截取", data.length, size);
	    byte[] newData = new byte[size];
	    System.arraycopy(data, 0, newData, 0, size);
	    data = newData;
	}
	out.write(data);
    }

}